package cn.codergege.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.codergege.shiro.dao.UserMapper;
import cn.codergege.shiro.model.User;

public class ShiroRealm extends AuthorizingRealm {

	private final Logger log = LoggerFactory.getLogger(ShiroRealm.class);

	@Autowired
	private UserMapper userMapper;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();

		User user = null;
		try {
			user = userMapper.selectByName(username);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("查询用户异常: " + e.getMessage());
		}

		if(null == user) {
			throw new UnknownAccountException("用户不存在!");
		}

		Object principal = user.getUsername();
		Object hashedCredentials = user.getPassword();
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getPasswordSalt());
		String realmName = getName();
//		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, realmName);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
		return info;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Object principal = principals.getPrimaryPrincipal();
		log.info("Primary principal: " + principal);
		
		Set<String> roles = new HashSet<String>();
		// 模拟从数据库中获取 roles
		roles.add("user");
		if("zhang".equals(principal)) {
			roles.add("admin");
		}
		
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);
		return simpleAuthorizationInfo;
	}

}
